<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="产品名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select
        v-model="listQuery.category"
        placeholder="分类"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option label="香薰" value="香薰" />
        <el-option label="香囊" value="香囊" />
        <el-option label="香包" value="香包" />
        <el-option label="其他" value="其他" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="Plus" @click="handleCreate">
        添加产品
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="图片" align="center" width="100">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center" />
      <el-table-column label="分类" prop="category" align="center" />
      <el-table-column label="价格" prop="price" align="center" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stock" align="center" width="100" />
      <el-table-column label="描述" prop="description" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.current"
        v-model:page-size="listQuery.size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加文创产品' : '编辑文创产品'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="70px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="temp.category" placeholder="请选择分类">
            <el-option label="香薰" value="香薰" />
            <el-option label="香囊" value="香囊" />
            <el-option label="香包" value="香包" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="temp.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="temp.stock" :min="0" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            v-bind="uploadConfig"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleUploadImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="temp.imageUrl" :src="temp.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { createProduct, deleteProduct, getProductList, updateProduct } from '../../api/creative-product';
import { beforeImageUpload, getUploadConfig, handleUploadSuccess } from '../../utils/upload';

// 列表数据
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  current: 1,
  size: 10,
  name: '',
  category: ''
})

// 表单数据
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const temp = reactive({
  id: undefined,
  name: '',
  category: '',
  price: 0,
  stock: 0,
  description: '',
  imageUrl: ''
})

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const { data } = await getProductList(listQuery)
    list.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('Failed to get product list:', error)
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleFilter = () => {
  listQuery.current = 1
  getList()
}

// 分页
const handleSizeChange = (val) => {
  listQuery.size = val
  getList()
}

const handleCurrentChange = (val) => {
  listQuery.current = val
  getList()
}

// 上传相关
const uploadConfig = getUploadConfig('creative')

const handleUploadImageSuccess = (response) => {
  const url = handleUploadSuccess(response)
  if (url) {
    temp.imageUrl = url
  }
}

// 添加
const handleCreate = () => {
  Object.assign(temp, {
    id: undefined,
    name: '',
    category: '',
    price: 0,
    stock: 0,
    description: '',
    imageUrl: ''
  })
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}

// 编辑
const handleUpdate = (row) => {
  Object.assign(temp, row)
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该产品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('Failed to delete product:', error)
    }
  })
}

// 创建数据
const createData = async () => {
  try {
    await createProduct(temp)
    dialogFormVisible.value = false
    ElMessage.success('添加成功')
    getList()
  } catch (error) {
    console.error('Failed to create product:', error)
  }
}

// 更新数据
const updateData = async () => {
  try {
    await updateProduct(temp)
    dialogFormVisible.value = false
    ElMessage.success('更新成功')
    getList()
  } catch (error) {
    console.error('Failed to update product:', error)
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 30px;
}

.dialog-footer {
  text-align: right;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 